"""
提供解析Excel 数据功能
"""
import os
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet
import csv
from common.logger import logger

BaseDir = os.path.dirname(os.path.dirname(__file__))
dataDir = os.path.join(BaseDir,"data")

class FileHandler():
    def __init__(self):
        self.data_dir=dataDir

    def do_Excel(self,excelpath:str,sheetname:str):
        """
        读取Excel文件，文件内容默认按行读取，读取结果存到list中
        :param excelpath:
        :param sheetname:
        :return:
        """
        #  testdata.xlsx文件路径
        excel_file = os.path.join(dataDir,excelpath)
        # 加载excel文件
        workbook=load_workbook(filename=excel_file)
        # 读取sheet
        worksheet:Worksheet = workbook[sheetname]
        logger.info(f'开始处理数据文件{excel_file}，sheet工作表{sheetname}')
        lists = []
        for row in worksheet.iter_rows(min_col=1,min_row=2,max_col=worksheet.max_column,max_row=worksheet.max_row,values_only=True):
            print(row)
            lists.append(row)
        return lists

    def do_CSV(self,csvpath:str):
        """
        读取csv文件
        :param csvpath:csv 文件路径
        :return:list数据格式
        """
        # csv文件路径
        csv_file = os.path.join(self.data_dir,csvpath)
        testdata = []
        with open(csv_file,'r',encoding='utf8') as f:
            # 去掉表头
            f.readline()
            read = csv.reader(f)
            for line in read:
                testdata.append(line)
        return testdata

    








# # testdata.xlsx文件路径
# excel_file = os.path.join(dataDir,"testdata.xlsx")
#
# # 加载excel文件
# workbook = load_workbook(filename=excel_file)
# # 获取“sheet1”表单
# worksheet:Worksheet = workbook.get_sheet_by_name("Sheet1")
# print(worksheet.sheetnames)
# # 获取sheet工作表中的行与列
# print('行',worksheet.columns,worksheet.max_column)
# print("列",worksheet.rows,worksheet.max_row)

